<?php
ini_set("soap.wsdl_cache_enabled", "0");
ini_set('display_errors', 0);
set_time_limit(0);
$arr_dir = explode('|', str_replace(array ('/','\\'), '|', __DIR__));
$str_dir = array_pop($arr_dir);
define('ORG_ID', $str_dir);
include_once dirname(dirname(dirname(__FILE__))) . '/mgtv_v2/mgtv_init.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/sp/sp.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/mgtv_v2/models/public_model_exec.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/mgtv_v2/models/video_model.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/c2_log/c2_log.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/c2_task/c2_task.class.php';
$ip = i_get_ip();
$postdata = file_get_contents("php://input");
// $postdata = '<message module="iCMS" version="1.0">
// <header timestamp="1506590732516" sequence="2017092817250004" component-id="iCMS_01" component-type="iCMS" action="REQUEST" command="DELIVERY_TASK_DONE"/>
//         <body>
//                 <tasks>
//   <task id="2017092817250004" original-content-id="JSB12028TI0000047965" content-id="JSB12028TI0000047965" subcontent-id="JSB12028MO0000082695" target-system-id="cncms" begin-time="2010-07-09T00:00:00.0Z" end-time="2010-07-09T01:00:00.0Z" status="6" >
//   <play-url>cvideo/test/20170918/59bf6e7f20422fa714a4552e539325d6/fb9bdc12cc23ab8cfc5709a72be05ca3.m3u8</play-url>
//      </task>
//                                                 </tasks>
//         </body>
// </message>';

// $postdata = '<message module="iCMS" version="1.0">
// 	<header timestamp="1530777977973" sequence="2018070516060002" component-id="iCMS_01" component-type="iCMS" action="REQUEST" command="DELIVERY_TASK_DONE"/>
// 	<body>
// 		<tasks>
// 				    		       <task id="2018070516060002" original-content-id="JSB12035PAPT00480460" content-id="JSB12035PAPT00480460" subcontent-id="JSB12035MV0000375803" target-system-id="cncms" begin-time="2010-07-09T00:00:00.0Z" end-time="2010-07-09T01:00:00.0Z" status="6" >
// 				<play-url>local_cache/mgtv/20180703/5b3b227322466060c927ef81c2395257/1a083d4e26a0db378b65bd9ddd5c9b79.ts</play-url>
// 			   </task>
// 		    				</tasks>
// 	</body>
// </message>';
$file_init_dir = dirname(dirname(dirname(__FILE__))) . '/mgtv_v2/' . ORG_ID . '/init.php';
$file_init_define = dirname(dirname(dirname(__FILE__))) . '/mgtv_v2/' . ORG_ID . '/define.php';
if(!file_exists($file_init_define) || !file_exists($file_init_dir))
{
	nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, '初始化文件不存在:[' . $file_init_dir . ']['.$file_init_define.']', 'public');
	echo "1|inner error";
	exit();
}
include_once $file_init_dir;
include_once $file_init_define;
nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, '--------------CDN到BK消息反馈开始--------------', ORG_ID);
nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, '执行文件:' . __FILE__, ORG_ID);
nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, '收到来自CDN的消息为空,IP:' . $ip . ';收到来自CDN的内容:' . $postdata, 'public');
nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, '收到来自CDN的消息为空,IP:' . $ip . ';收到来自CDN的POST内容:' . var_export($_REQUEST,true), 'public');
class notify_cdi
{
    private $int_sequence;

    public function set_sequence($int_sequence)
    {
        $this->int_sequence = $int_sequence;
    }
    public function get_sequence()
    {
        return $this->int_sequence;
    }

	public function ContentDeployResult($CMSID, $SOPID, $CorrelateID, $ResultCode,$ErrorDescription,$ResultContent,$media_id)
	{
	    $result_task_id = $this->get_source_id($media_id);
	    $arg_list = func_get_args();
	    nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '方法参数：' . var_export($arg_list, true), ORG_ID);
	    if($result_task_id !== false)
	    {
    		$c2_notify = array (
    			'nns_id' => $result_task_id, 
    			'nns_notify_content' => $ResultContent, 
    			'nns_notify_result' => $ResultCode,
    	        'nns_error_description'=> $ErrorDescription,
    	        'nns_notify_result_url'=>'',
    		    'nns_notify_PlayId' => $media_id,
    		);
    		$result = c2_task_model::save_c2_notify_v2($c2_notify);
    		nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '修改C2表参数：' . var_export($c2_notify, true), ORG_ID);
    		nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . 'log结果：' . var_export($result, true), ORG_ID);
	    }
	    else 
	    {
	        $result = array('ret'=>0,'reason'=>'ok');
	    }
		$str_response_result = $this->get_response($result);
		nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '结果：' . var_export($str_response_result, true), ORG_ID);
		return $str_response_result;
	}

	/**
	 * 获取原始日志ID
	 * @param unknown $media_id
	 */
	public function get_source_id($media_id)
	{
	    $dc = nl_get_dc(array (
                'db_policy' => NL_DB_WRITE,
                'cache_policy' => NP_KV_CACHE_TYPE_NULL
            ));
	    $result = public_model_exec::get_asset_id_by_sp_import_id(ORG_ID, 'media', $media_id);
	    if(!isset($result['data_info']['data_info']) || !is_array($result['data_info']['data_info']) || empty($result['data_info']['data_info']))
	    {
	        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '通过片源注入ID反查片源信息失败：' . var_export($result, true), ORG_ID);
	        return false;
	    }
	    $result = $result['data_info']['data_info'];
	    $result_c2_task = nl_c2_task::query_c2_exsist($dc, 'media', $result['nns_id'], ORG_ID);
	    if(!isset($result_c2_task['data_info'][0]) || empty($result_c2_task['data_info'][0]) || !is_array($result_c2_task['data_info'][0]))
	    {
	        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '通过片源查询C2_task表信息失败：' . var_export($result_c2_task, true), ORG_ID);
	        return false;
	    }
	    $result_c2_task = $result_c2_task['data_info'][0];
	    $result_c2_task_log = nl_c2_log::query_by_task_id($dc, $result_c2_task['nns_id']);
	    if(!isset($result_c2_task_log['data_info'][0]) || empty($result_c2_task_log['data_info'][0]) || !is_array($result_c2_task_log['data_info'][0]))
	    {
	        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '通过片源查询C2_task_log表信息失败：' . var_export($result_c2_task_log, true), ORG_ID);
	        return false;
	    }
	    $result_c2_task_log = $result_c2_task_log['data_info'][0];
	    return (isset($result_c2_task_log['nns_id']) && strlen($result_c2_task_log['nns_id']) >0) ? $result_c2_task_log['nns_id'] : false;
	}
	
	
	/**
	 * 消息反馈
	 * @param unknown $arr_result
	 * @return string
	 */
	private function get_response($arr_result)
    {
        $arr_result=array('ret'=>0,'reason'=>'ok');

        $str_code = $str_description = '';
        $str_code = ($arr_result['ret'] == 0) ? 1: 0;
        $str_description = empty($arr_result['reason']) ? 'fail' : 'ok';

        $int_timestamp = $this->get_java_datetime();
        $sequence = $this->get_sequence();
        $str_response = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<message module="iCMS" version="1.0">
    <header timestamp="{$int_timestamp}" sequence="{$sequence}" component-id="iCMS" component-type="iCMS" action="RESPONSE" command="DELIVERY_TASK_DONE"/>
    <body>
    <result code="{$str_code}" description="{$str_description}"/>
    </body>
</message>
XML;
        return $str_response;
    }

    /**
     * 思华-转换成Java的时间格式
     * @author <feijian.gao@starcor.com>
     * @date    2017年9月1日14:57:55
     * @return false|mixed|string
     */
    private function get_java_datetime()
    {
        $time = time();
        $date = date('c',time());
        $date_zone_replace = date('O',time());
        $date_zone_search = date('P',time());
        $date = str_replace($date_zone_search,$date_zone_replace,$date);
        $date = str_replace("+",". ",$date);
        return $date;
    }
}
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadXML($postdata);
$header = $dom->getElementsByTagName('header');
$task = $dom->getElementsByTagName('task');
if($header->length <1)
{
    echo "1|header error";
	exit();
}
if($task->length <1)
{
    echo "1|task error";
    exit();
}
$command = '';
$arr_task = null;
foreach ($header as $header_val)
{
    $sequence = $header_val->getAttribute('sequence');
    $command = $header_val->getAttribute('command');
    if(strlen($sequence) >0 && $command=='DELIVERY_TASK_DONE')
    {
        break;
    }
}
if($command != 'DELIVERY_TASK_DONE' && $command != 'WITHDRAWAL_TASK_DONE')
{
    echo "1|command error";
    exit();
}
foreach ($task as $task_val)
{
    $id = $task_val->getAttribute('id');
    $status = $task_val->getAttribute('status');
    $media_id = $task_val->getAttribute('subcontent-id');
    if(strlen($id) <1 || strlen($media_id) <1)
    {
        continue;
    }
    if($command == 'DELIVERY_TASK_DONE')
    {
        $arr_task[] = array(
            'nns_id'=>$id,
            'nns_media_id'=>$media_id,
            'nns_notify_result'=>($status == '6') ? 0 : '-1',
            'nns_notify_content'=>$postdata,
            'nns_error_description'=>$status,
        );
    }
    else
    {
        $arr_task[] = array(
            'nns_id'=>$id,
            'nns_media_id'=>$media_id,
            'nns_notify_result'=>($status == '4') ? 0 : '-1',
            'nns_notify_content'=>$postdata,
            'nns_error_description'=>$status,
        );
    }
}
if(empty($arr_task) || !is_array($arr_task))
{
    echo "1|task empty";
    exit();
}
foreach ($arr_task as $task_val)
{
    $obj_notify = new notify_cdi();
    $obj_notify->set_sequence($sequence);
    $result = $obj_notify->ContentDeployResult('starcor', ORG_ID, $task_val['nns_id'], $task_val['nns_notify_result'], $task_val['nns_error_description'], $task_val['nns_notify_content'],$task_val['nns_media_id']);
    nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, '处理结果:'.var_export($result,true), ORG_ID);
    unset($obj_notify);
    $obj_notify = null;
}
echo $result;
nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, '--------------CDN到BK消息反馈结束--------------', ORG_ID);